import psutil

from applications.common.utils.file_utils import human_readable_size, calculate_total_size


def mem_size():
    mem = psutil.virtual_memory()
    return {
        "total_physical_memory": mem.total,
        "available_physical_memory": mem.available,
        "total_virtual_memory": psutil.swap_memory().total + mem.total,
        "available_virtual_memory": psutil.swap_memory().free + mem.available,
        "swap_memory": psutil.swap_memory().total
    }


def mem_size_str():
    mem = mem_size()
    return {
        "total_physical_memory": human_readable_size(mem["total_physical_memory"]),
        "available_physical_memory": human_readable_size(mem["available_physical_memory"]),
        "total_virtual_memory": human_readable_size(mem["total_virtual_memory"]),
        "available_virtual_memory": human_readable_size(mem["available_virtual_memory"]),
        "swap_memory": human_readable_size(mem["swap_memory"])
    }


info = mem_size_str()
print(f"# ------------内存情况------------")
print(f"# 总物理内存: {info['total_physical_memory']}")
print(f"# 可用物理内存: {info['available_physical_memory']}")
print(f"# 交换空间大小: {info['swap_memory']}")
print(f"# 总虚拟内存: {info['total_virtual_memory']}")
print(f"# 可用虚拟内存: {info['available_virtual_memory']}")
print(f"# -------------------------------")
print("\n")


def memory_access_by_size(size, ix=0.7):
    mem = psutil.virtual_memory()
    if (psutil.swap_memory().free + mem.available * ix) < size:
        return False
    return True


def memory_access_by_paths(paths, ix=0.7):
    return memory_access_by_size(calculate_total_size(paths), ix)


def memory_access_available_h(ix=0.7):
    mem = psutil.virtual_memory()
    return human_readable_size(psutil.swap_memory().free + mem.available * ix)


def memory_access_available(ix=0.7):
    mem = psutil.virtual_memory()
    return psutil.swap_memory().free + mem.available * ix
